using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;

namespace WPFTemplateLib.CustomKeyboard
{
	public partial class NumberKeyboard : KeyboardWindowBase
	{
		#region 成员

		/// <summary>
		/// 获取字符串值
		/// </summary>
		public override string StringValue => TbInput.Text;

		/// <summary>
		/// 获取小数值
		/// </summary>
		public double? DoubleValue => string.IsNullOrEmpty(TbInput.Text) ? null : double.Parse(TbInput.Text);

		/// <summary>
		/// 获取整数值
		/// </summary>
		public int? IntValue => string.IsNullOrEmpty(TbInput.Text) ? null : int.Parse(TbInput.Text);

		public NumberKeyboard(string originValue) : base(originValue)
		{
			InitializeComponent();

			TbInput.Text = OriginValue;
			TbInput.SelectAll();
		}

		#endregion

		private void Btn_Click(object sender, RoutedEventArgs e)
		{
			string tag = ((System.Windows.Controls.Button)e.Source).Tag.ToString();
			switch(tag)
			{
				case "1":
				case "2":
				case "3":
				case "4":
				case "5":
				case "6":
				case "7":
				case "8":
				case "9":
				case "0":
				{
					string inputText = tag;
					if(string.IsNullOrEmpty(TbInput.SelectedText))
					{
						TbInput.Text = TbInput.Text.Insert(TbInput.CaretIndex, inputText);
					}
					else
					{
						TbInput.SelectedText = inputText;
					}

					BtnOk.Focus();
					TbInput.CaretIndex = TbInput.Text.Length;
					break;
				}
				case "Del":
					var length = TbInput.Text.Length;
					if(length > 0)
					{
						if(string.IsNullOrEmpty(TbInput.SelectedText))
						{
							TbInput.Text = TbInput.Text.Remove(length - 1);
						}
						else
						{
							TbInput.SelectedText = string.Empty;
						}

						TbInput.CaretIndex = TbInput.Text.Length;
					}
					break;
				case "-":
					if(!TbInput.Text.Contains("-"))
					{
						TbInput.Text = TbInput.Text.Insert(0, "-");
					}
					else
					{
						TbInput.Text = TbInput.Text.Replace("-", "");
					}

					TbInput.CaretIndex = TbInput.Text.Length;
					break;
				case ".":
					if(TbInput.Text.Length > 0 && !TbInput.Text.Contains("."))
					{
						TbInput.Text += ".";
						TbInput.CaretIndex = TbInput.Text.Length;
					}
					break;
				case "Clear":
					TbInput.Text = "";
					break;
				case "OK":
					DialogResult = true;
					Close();
					break;
				case "Cancel":
					Close();
					break;
				default:
					break;
			}
		}

		private void TbInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
		{
			e.Handled = new Regex("[^0-9.-]+").IsMatch(e.Text);
		}

		private void TbInput_OnKeyUp(object sender, KeyEventArgs e)
		{
			if(e.Key == Key.Enter)
			{
				DialogResult = true;
				Close();
			}
			//else if(e.Key == Key.Escape)
			//{
			//	Close();
			//}
		}
	}
}
